package com.lhb.rabbit.message;

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.context.annotation.Bean;

public class Message {

    public static class SelfMessageConvert extends AbstractMessageConverter
    {

        @Override
        protected org.springframework.amqp.core.Message createMessage(Object o, MessageProperties messageProperties) {

            messageProperties.setContentType("application/json");
            return new org.springframework.amqp.core.Message(JSON.toJSONBytes(o),messageProperties);
        }

        @Override
        public Object fromMessage(org.springframework.amqp.core.Message message) throws MessageConversionException {
            return JSON.parse(message.getBody());
        }
    }

    @Bean
    public RabbitTemplate jsonRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new SelfMessageConvert());
        return rabbitTemplate;
    }
}
